<template>
	<view class="home-page">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<uni-search-bar 
				v-model="searchKeyword" 
				@confirm="handleSearch"
				@input="handleSearchInput"
				placeholder="搜索闲置物品"
				cancel-button="none"
				bg-color="#F5F5F5"
			/>
		</view>

		<!-- 轮播图 -->
		<view class="banner-section">
			<swiper class="banner-swiper" autoplay circular indicator-dots>
				<swiper-item class="banner-item">
					<view class="sale-banner">
						<text class="sale-text">SALE</text>
						<text class="sale-desc">955 %. OORS</text>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 分类导航 -->
		<view class="category-section">
			<scroll-view class="category-scroll" scroll-x>
				<view class="category-list">
					<view 
						v-for="category in categories" 
						:key="category.id"
						class="category-item"
						:class="{ active: selectedCategoryId === category.id }"
						@click="selectCategory(category.id)"
					>
						<image class="category-icon" :src="category.icon" mode="aspectFit" />
						<text class="category-name">{{ category.name }}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 热门闲置标题 -->
		<view class="section-title">
			<text class="title-text">热门闲置</text>
			<view class="title-line"></view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-section">
			<view class="goods-grid">
				<view 
					v-for="goods in goodsList" 
					:key="goods.id"
					class="goods-item"
					@click="goToDetail(goods.id)"
				>
					<view class="goods-image-wrapper">
						<image 
							class="goods-image" 
							:src="goods.images[0]" 
							mode="aspectFill"
							lazy-load
						/>
					</view>
					<view class="goods-info">
						<text class="goods-title">{{ goods.title }}</text>
						<view class="goods-price-row">
							<text class="goods-price">¥{{ goods.price }}</text>
							<text v-if="goods.originalPrice" class="original-price">¥{{ goods.originalPrice }}</text>
						</view>
						<view class="goods-seller">
							<image class="seller-avatar" :src="goods.sellerAvatar" mode="aspectFill" />
							<text class="seller-name">{{ goods.sellerName }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="loading" class="loading-more">
				<uni-load-more status="loading" />
			</view>
			<view v-else-if="!hasMore" class="no-more">
				<text>没有更多了</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { getGoodsList, getGoodsCategories } from '../../api/goods'
import type { GoodsItem, GoodsCategory } from '../../types/goods'
import { CATEGORY_ICONS } from '../../utils/config'

// 响应式数据
const searchKeyword = ref('')
const selectedCategoryId = ref('')
const categories = ref<GoodsCategory[]>([])
const goodsList = ref<GoodsItem[]>([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 10

// 初始化分类数据
const initCategories = () => {
	categories.value = [
		{ id: '', name: '全部', icon: '/static/c9.png', sort: 0 },
		{ id: '1', name: '服装', icon: '/static/c1.png', sort: 1 },
		{ id: '2', name: '书籍', icon: '/static/c2.png', sort: 2 },
		{ id: '3', name: '数码', icon: '/static/c3.png', sort: 3 },
		{ id: '4', name: '家居', icon: '/static/c4.png', sort: 4 }
	]
}

// 初始化商品数据（模拟数据）
const initGoodsData = () => {
	goodsList.value = [
		{
			id: '1',
			title: '牛仔外套',
			description: '九成新牛仔外套，质量很好',
			price: 89,
			originalPrice: 199,
			images: ['/static/c1.png'],
			categoryId: '1',
			categoryName: '服装',
			status: 'available' as const,
			sellerId: '1',
			sellerName: '张女士',
			sellerAvatar: '/static/logo.png',
			location: '北京市朝阳区',
			viewCount: 128,
			favoriteCount: 15,
			isFavorite: false,
			publishTime: '2024-01-15T10:30:00Z',
			updateTime: '2024-01-15T10:30:00Z'
		},
		{
			id: '2',
			title: '蓝牙耳机',
			description: '全新未拆封蓝牙耳机',
			price: 129,
			originalPrice: 299,
			images: ['/static/c3.png'],
			categoryId: '3',
			categoryName: '数码',
			status: 'available' as const,
			sellerId: '2',
			sellerName: '李先生',
			sellerAvatar: '/static/logo.png',
			location: '上海市浦东新区',
			viewCount: 89,
			favoriteCount: 8,
			isFavorite: false,
			publishTime: '2024-01-14T15:20:00Z',
			updateTime: '2024-01-14T15:20:00Z'
		}
	]
}

// 搜索处理
const handleSearch = () => {
	console.log('搜索:', searchKeyword.value)
	// TODO: 实现搜索逻辑
}

const handleSearchInput = (value: string) => {
	searchKeyword.value = value
}

// 分类选择
const selectCategory = (categoryId: string) => {
	selectedCategoryId.value = categoryId
	console.log('选择分类:', categoryId)
	// TODO: 根据分类筛选商品
}

// 跳转到商品详情
const goToDetail = (goodsId: string) => {
	uni.navigateTo({
		url: `/pages/goods/detail?id=${goodsId}`
	})
}

// 加载商品列表
const loadGoodsList = async (refresh = false) => {
	if (loading.value) return
	
	loading.value = true
	
	try {
		// TODO: 调用真实API
		// const response = await getGoodsList({
		// 	page: currentPage.value,
		// 	pageSize,
		// 	categoryId: selectedCategoryId.value || undefined,
		// 	keyword: searchKeyword.value || undefined
		// })
		
		// 模拟API延迟
		await new Promise(resolve => setTimeout(resolve, 1000))
		
		if (refresh) {
			currentPage.value = 1
			goodsList.value = []
		}
		
		// 这里使用模拟数据，实际开发中替换为API调用
		if (currentPage.value === 1) {
			initGoodsData()
		}
		
		currentPage.value++
	} catch (error) {
		console.error('加载商品列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 页面生命周期
onMounted(() => {
	initCategories()
	loadGoodsList()
})

// 下拉刷新
onPullDownRefresh(() => {
	loadGoodsList(true).finally(() => {
		uni.stopPullDownRefresh()
	})
})

// 上拉加载更多
onReachBottom(() => {
	if (hasMore.value) {
		loadGoodsList()
	}
})
</script>

<style lang="scss" scoped>
.home-page {
	background-color: #F5F5F5;
	min-height: 100vh;
}

.search-bar {
	padding: 20rpx;
	background-color: #FFFFFF;
}

.banner-section {
	margin: 20rpx;
	border-radius: 16rpx;
	overflow: hidden;
}

.banner-swiper {
	height: 300rpx;
}

.banner-item {
	height: 100%;
}

.sale-banner {
	height: 100%;
	background: linear-gradient(135deg, #FFE066 0%, #07C160 100%);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	color: white;
}

.sale-text {
	font-size: 60rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.sale-desc {
	font-size: 28rpx;
}

.category-section {
	padding: 20rpx 0;
	background-color: #FFFFFF;
	margin-bottom: 20rpx;
}

.category-scroll {
	white-space: nowrap;
}

.category-list {
	display: flex;
	padding: 0 20rpx;
}

.category-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-right: 40rpx;
	padding: 20rpx;
	border-radius: 12rpx;
	transition: all 0.3s;
	
	&.active {
		background-color: #E8F5E8;
		
		.category-name {
			color: #07C160;
		}
	}
}

.category-icon {
	width: 60rpx;
	height: 60rpx;
	margin-bottom: 10rpx;
}

.category-name {
	font-size: 24rpx;
	color: #666666;
}

.section-title {
	display: flex;
	align-items: center;
	padding: 0 20rpx 20rpx;
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-right: 20rpx;
}

.title-line {
	flex: 1;
	height: 4rpx;
	background-color: #07C160;
	border-radius: 2rpx;
}

.goods-section {
	padding: 0 20rpx;
}

.goods-grid {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
}

.goods-item {
	width: 48%;
	background-color: #FFFFFF;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.goods-image-wrapper {
	width: 100%;
	height: 280rpx;
	position: relative;
}

.goods-image {
	width: 100%;
	height: 100%;
}

.goods-info {
	padding: 20rpx;
}

.goods-title {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	line-height: 1.4;
	margin-bottom: 10rpx;
}

.goods-price-row {
	display: flex;
	align-items: center;
	margin-bottom: 15rpx;
}

.goods-price {
	font-size: 32rpx;
	color: #FF4444;
	font-weight: bold;
	margin-right: 10rpx;
}

.original-price {
	font-size: 24rpx;
	color: #999999;
	text-decoration: line-through;
}

.goods-seller {
	display: flex;
	align-items: center;
}

.seller-avatar {
	width: 32rpx;
	height: 32rpx;
	border-radius: 50%;
	margin-right: 10rpx;
}

.seller-name {
	font-size: 24rpx;
	color: #666666;
}

.loading-more {
	padding: 40rpx 0;
	text-align: center;
}

.no-more {
	padding: 40rpx 0;
	text-align: center;
	color: #999999;
	font-size: 24rpx;
}
</style>
